package pl.grabar.clinic.client.web.actions.admin.users;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import pl.grabar.clinic.core.dao.Dao;
import pl.grabar.clinic.core.domain.person.User;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Action("delete")
@InterceptorRef("grabarStack")
@Results({ @Result(name = "success", type = "redirectAction", location = "list"), @Result(name = "input", type = "redirectAction", location = "list") })
public class DeleteUserAction extends ActionSupport implements Preparable {

	private static final long serialVersionUID = 5203333642883335850L;

	private static final Log LOG = LogFactory.getLog(DeleteUserAction.class);

	@Autowired
	private Dao<User> userDao;

	private User user;

	private String userId;

	@Override
	public void prepare() throws Exception {
		user = userDao.findById(userId);
	}

	@Override
	public void validate() {
		if (!hasErrors()) {
			if (user == null) {
				addActionError(getText("pl.grabar.clinic.client.web.admin.users.actions.no-such-user"));
				LOG.error("Blad walidacji w trakcie usuwania uzytkownika. Uzytkownik o podanym id nie istnieje: " + userId);
			}
		}
	}

	@Override
	public String execute() throws Exception {
		userDao.delete(user);
		addActionError(getText("pl.grabar.clinic.client.web.admin.users.actions.delete.deleted", new String[] { user.getFullName() }));
		LOG.error("Usinieto uzytkownika o podanym id: " + userId + ":" + user.getFullName());
		return SUCCESS;
	}

	/* AKCESORY */

	public void setUserDao(Dao<User> userDao) {
		this.userDao = userDao;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

}
